import { Injectable } from '@nestjs/common'
import { RedisService } from 'src/redis/redis.service'

import { RankDTO } from './rank.dto'

@Injectable()
export class RankService {
  constructor(private readonly redisService: RedisService) {}
  save(data: RankDTO) {
    this.redisService.client.hmset('data', data)
    return this.redisService.client.zincrby('rank', data.score, data.nickname)
  }

  async list(size = 100) {
    const list = await this.redisService.client.zrevrangebyscore('rank', '+inf', '-inf', 'WITHSCORES', 'LIMIT', 0, size)

    const result: RankDTO[] = []
    for (let i = 0; i < list.length; i += 2) {
      result.push({ nickname: list[i], score: Number(list[i + 1]) })
    }

    return {
      size,
      title: '排行版',
      rank: result
    }
  }
}
